import { createWindow, loadUrl } from "./browser"
import axios from "axios";
import store from "electron-store"
// import { Font } from 'fonteditor-core';
const Font = require('fonteditor-core').Font;
const inflate = require('../assert/js/pako_inflate.min');

export class Content {
    url: string
    win!: Electron.BrowserWindow
    link: Array<string> = []
    zifu:any = {
        "&#xf008": "0",
        "&#x31": "1",
        "&#xe998": "2",
        "&#xedc9": "3",
        "&#xefe9": "4",
        "&#xf280": "5",
        "&#xe200": "6",
        "&#xefaf": "7",
        "&#xf1ec": "8",
        "&#xe728": "9",
        "&#x2d": "-",
        "&#x2c": ","
    }
    svgMap:any = {};
    woff_string = `
        1234567890店中美家馆
        小车大市公酒行国品发电金心业商司
        超生装园场食有新限天面工服海华水
        房饰城乐汽香部利子老艺花专东肉菜
        学福饭人百餐茶务通味所山区门药银
        农龙停尚安广鑫一容动南具源兴鲜记
        时机烤文康信果阳理锅宝达地儿衣特
        产西批坊州牛佳化五米修爱北养卖建
        材三会鸡室红站德王光名丽油院堂烧
        江社合星货型村自科快便日民营和活
        童明器烟育宾精屋经居庄石顺林尔县
        手厅销用好客火雅盛体旅之鞋辣作粉
        包楼校鱼平彩上吧保永万物教吃设医
        正造丰健点汤网庆技斯洗料配汇木缘
        加麻联卫川泰色世方寓风幼羊烫来高
        厂兰阿贝皮全女拉成云维贸道术运都
        口博河瑞宏京际路祥青镇厨培力惠连
        马鸿钢训影甲助窗布富牌头四多妆吉
        苑沙恒隆春干饼氏里二管诚制售嘉长
        轩杂副清计黄讯太鸭号街交与叉附近
        层旁对巷栋环省桥湖段乡厦府铺内侧
        元购前幢滨处向座下臬凤港开关景泉
        塘放昌线湾政步宁解白田町溪十八古
        双胜本单同九迎第台玉锦底后七斜期
        武岭松角纪朝峰六振珠局岗洲横边济
        井办汉代临弄团外塔杨铁浦字年岛陵
        原梅进荣友虹央桂沿事津凯莲丁秀柳
        集紫旗张谷的是不了很还个也这我就
        在以可到错没去过感次要比觉看得说
        常真们但最喜哈么别位能较境非为欢
        然他挺着价那意种想出员两推做排实
        分间甜度起满给热完格荐喝等其再几
        只现朋候样直而买于般豆量选奶打每
        评少算又因情找些份置适什蛋师气你
        姐棒试总定啊足级整带虾如态且尝主
        话强当更板知己无酸让入啦式笑赞片
        酱差像提队走嫩才刚午接重串回晚微
        周值费性桌拍跟块调糕
        `

    constructor(url: string, win?:Electron.BrowserWindow) {
        this.url = url
    }

    async init(key:string) {
        this.win = await createWindow(this.url, key)
        this.win.webContents.on('did-fail-load', () => {
            this.getContent(key)
        })
        this.win.webContents.on('unresponsive', () => {
            this.getContent(key)
        })
    }

    setUrl(url: string):Content {
        this.url = url

        return this
    }

    async getContent(key:string) {
        await loadUrl(this.win, this.url, key)
        let content = await this.win.webContents.executeJavaScript("function " + this.getContentJsV2.toString()+ "; getContentJsV2();")
        console.log(content);
        if (content == null) {
            return null
        }
        content.url = this.url
        let result = await this.decodeV2(content);
        console.log("getContent", result);
        return result
    }

    async decodeV2(content: any) {
        const storage = new store();
        let woffMap: any = storage.get("woff") || {};
        const phone = content.phone.trim();
        const address = content.address.trim();
        const svgTextCssLink = storage.get('svgtextcsslink', '');
        console.log("svgTextCssLink", svgTextCssLink);
        if(svgTextCssLink != content.svgTextCssLink) {
            // 不等于 就下载woff
            const woffLink = await this.getWoffLink(content.svgTextCssLink);
            woffMap =  await this.woffToZifu(woffLink);
            storage.set("svgtextcsslink", content.svgTextCssLink)
        }
        
        content.phone = this.stringToEntity(phone, 0).split(";").map((item, key) => {
            return woffMap[item] || phone[key]
        }).join("");
        // console.log(" stringToEntity", this.stringToEntity(address, 0))
        content.address = this.stringToEntity(address, 0).split(";").map((item, key) => {
            return woffMap[item] || address[key]
        }).join("");

        console.log("content", content);
        return content;
    }

    public stringToEntity(str:string, radix:number) {
        let arr = str.split('')
        radix = radix || 0
        let tmp = arr.map(item =>
            `${(radix ? "x" + item.charCodeAt(0).toString(16) : item.charCodeAt(0))};`).join('')
        // console.log(`'${str}' 转实体为 '${tmp}'`)
        return tmp
    }

    public getContentJsV2() {
        try {
            //
            let svglink: any = document.querySelectorAll('link[rel="stylesheet"]')[1];
            let href = svglink.href;
            let areas = (<any>document.querySelectorAll(".breadcrumb")[0]).textContent.match(/[\u4e00-\u9fa5]+? /g);

            document.querySelectorAll("#basic-info > p > span").length > 0 &&
            document.querySelectorAll("#basic-info > p > span")[0].remove();

            let res = document.querySelectorAll("#basic-info > p")
            //let res = phone != null ? phone.match(/(\d{11}|(\d{3,4}-)?\d{8})/) : null
            if (res.length == 0) {
                return null
            }
            let phone = res[0].textContent

            let address = document.querySelectorAll("#address")[0].textContent
            // 标题
            document.querySelectorAll("#basic-info > h1 > a")[0].remove()
            let name = (<string>document.querySelectorAll("#basic-info > h1")[0].textContent).trim()
            name = name != null ? name : ""

            return {
                phone: phone,
                address: address,
                name: name,
                svgTextCssLink: href,
                area: [areas.length > 2 ? areas[2] : '', areas.length > 3 ? areas[3] : '']
            }
        } catch (error) {
            console.log(error);
            return null
        }
    }

    public async getWoffLink(svglink: string) {
        let res = await axios({
            url: svglink,
            method: "GET"
        });
        let mat = "http:" + res.data.match(/,url\(\"(.*?woff)\"/)[1];
        return mat;
    }

    public async woffToZifu(url: string) {
        const storage = new store();
        let res = await axios({
            url: url,
            method: "GET",
            responseType: 'arraybuffer'
        });
        var font = Font.create(res.data, {
            type: 'woff', // support ttf,woff,eot,otf,svg
            inflate: inflate.inflate
        });
        const cmap = font.data.cmap; // {120: 1, 57349: 416}
        const woffString = this.woff_string.replace(/\s+/g, "").split("");
        // console.log(cmap);
        let result: any = {};
        Object.keys(cmap).map((item) => {
            result[item] = cmap[item] - 2 > 0 ? woffString[ cmap[item] - 2 ] : "";
        })
        storage.set("woff", result);
        console.log("woff", result);
        return result;
    }
}